package com.example.safeassistan.home.fragment;

import android.content.Context;
import android.graphics.drawable.BitmapDrawable;
import android.os.Build;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.RequiresApi;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.example.safeassistan.R;
import com.example.safeassistan.UserInfoModel;
import com.example.safeassistan.base.BaseVPFragment;
import com.example.safeassistan.common.UserData;
import com.example.safeassistan.constants.UrlConstants;
import com.example.safeassistan.hiddendanger.activity.HiddendangerUnSubmit;
import com.example.safeassistan.hiddendanger.adapter.HiddenDangerStatusAdapter;
import com.example.safeassistan.hiddendanger.model.StatusModel;
import com.example.safeassistan.home.activity.OverDueHiddenDangerDetail;
import com.example.safeassistan.home.adapter.RiskDetailHiddenFragmentAdapter;
import com.example.safeassistan.http.HttpRequest;
import com.example.safeassistan.http.HttpStringCallBack;
import com.example.safeassistan.risk.model.RiskDetailHiddenDanger;
import com.example.safeassistan.utile.JsonUtils;
import com.example.safeassistan.widget.ViewPagerForScrollView;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

public class RiskDetailHiddendangerFragment extends BaseVPFragment implements View.OnClickListener {
    private Context context;
    private View view;
    private RiskDetailHiddenFragmentAdapter adapter;
    private List<RiskDetailHiddenDanger.ResultDTO> data;
    private RecyclerView rcView;
    private LinearLayout llCheckTable,llCheckResult;
    private TextView tvCheckTable,tvCheckResult;
    private ViewPagerForScrollView pager;

    private Integer level=-1;//1 一般 3重大
    private Integer disposeStatus=-1;//隐患状态 1、待提交 2、待评审 3、待整改 4、待验收 5、已完成 6、已撤销
    private String riskPointId="";//风险点id
    private List<StatusModel> ststusUnHandle;
    HiddenDangerStatusAdapter statusAdapter;

    public RiskDetailHiddendangerFragment(ViewPagerForScrollView pager,String riskPointId) {
        this.pager = pager;
        this.riskPointId=riskPointId;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        if (view == null) {
            view = inflater.inflate(R.layout.riskdetail_hiddendanger_fragment, container, false);
            pager.setObjectForPosition(view,4);
            context = getActivity();
            initView();
        }
        return view;
    }

    public void initView(){
        rcView=view.findViewById(R.id.rcView);
        llCheckResult=view.findViewById(R.id.llCheckResult);
        llCheckTable=view.findViewById(R.id.llCheckTable);
        tvCheckTable=view.findViewById(R.id.tvCheckTable);
        tvCheckResult=view.findViewById(R.id.tvCheckResult);
        llCheckTable.setOnClickListener(this::onClick);
        llCheckResult.setOnClickListener(this);

        data=new ArrayList<>();
        ststusUnHandle=new ArrayList<>();
        ststusUnHandle.add(new StatusModel("待提交",1));
        ststusUnHandle.add(new StatusModel("待评审",2));
        ststusUnHandle.add(new StatusModel("待整改",3));
        ststusUnHandle.add(new StatusModel("待验收",4));
        ststusUnHandle.add(new StatusModel("已完成",5));
        ststusUnHandle.add(new StatusModel("已撤销",6));
    }

    @Override
    protected void onFragmentVisibleChange(boolean isVisible) {

    }

    @Override
    protected void onFragmentFirstVisible() {
        getData();
    }

    public void getData(){
        JSONObject map = new JSONObject();
        try {
            if (level!=-1){
                map.put("level",level);//隐患等级
            }
            map.put("riskPointId",riskPointId);//风险点id
            if (disposeStatus!=-1){
                map.put("disposeStatus",disposeStatus);
            }

        } catch (JSONException e) {
            e.printStackTrace();
        }

        new HttpRequest(context).doPost(UrlConstants.queryHiddenDangerByRisk, null, map, new HttpStringCallBack() {
            @RequiresApi(api = Build.VERSION_CODES.M)
            @Override
            public void onSuccess(Object result) {
                String datas = result.toString();
                JSONObject jsonObject = null;
                try {
                    jsonObject = new JSONObject(datas);
                    String message = jsonObject.getString("message");
                    Boolean success = jsonObject.getBoolean("success");
                    if (success) {
                        Object obj = JsonUtils.fromJson(result.toString(), RiskDetailHiddenDanger.class);
                        if (obj instanceof RiskDetailHiddenDanger) {
                            RiskDetailHiddenDanger model=(RiskDetailHiddenDanger) obj;
                            data.clear();
                            if (model.getResult().size() > 0) {
                                data=model.getResult();


                                LinearLayoutManager linearLayoutManager=new LinearLayoutManager(context,RecyclerView.VERTICAL,false){
                                    @Override
                                    public boolean canScrollVertically() {
                                        return false;
                                    }
                                };
                                rcView.setLayoutManager(linearLayoutManager);
                                adapter=new RiskDetailHiddenFragmentAdapter(data);
                                rcView.setAdapter(adapter);
                                adapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
                                    @Override
                                    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                                        switch (data.get(position).getDisposeStatus()+""){
                                            case "1":
                                                //隐患添加页面
                                                getUserInfo();
                                                HiddendangerUnSubmit.actionStart(context,model.getResult().get(position).getId(),riskPointId,1);
                                                break;
                                            default:
                                                OverDueHiddenDangerDetail.actionStart(context,
                                                        model.getResult().get(position).getDisposeStatus()+"",
                                                        1,model.getResult().get(position).getId()
                                                        ,model.getResult().get(position).getRectSubmit());
                                         break;
                                        }
                                    }
                                });
                                rcView.setNestedScrollingEnabled(false);
                            } else {
                                adapter.notifyDataSetChanged();
                            }
                        }
                    }else {
                        Toast.makeText(context,message,Toast.LENGTH_SHORT).show();
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(int code, String msg) {

            }
        });
    }

    public  void getUserInfo() {
        new HttpRequest(context).doGet(UrlConstants.userInfoqueryPersonage, null,new HttpStringCallBack() {
            @Override
            public void onSuccess(Object result) {
                try {
                    String data = result.toString();
                    //把请求得数据转换成json对象
                    JSONObject jsonObject = null;
                    jsonObject = new JSONObject(data);
                    String message = jsonObject.getString("message");
                    Boolean success=jsonObject.getBoolean("success");
                    if(success){
                        Object obj = JsonUtils.fromJson(result.toString(), UserInfoModel.class);
                        if (obj instanceof UserInfoModel) {
                            UserInfoModel model = (UserInfoModel) obj;
                            UserData.create(context).saveUserData(model.getResult());
                        }
                    }else {
                        Toast.makeText(context,message,Toast.LENGTH_SHORT).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(int code, String msg) { }
        });
    }


    private PopupWindow popupWindow;
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.llCheckResult:
                View inflate1 = LayoutInflater.from(context).inflate(R.layout.popu_hiddendanger_level,null);
                TextView tvBig=inflate1.findViewById(R.id.tvUn);
                TextView tvCommon=inflate1.findViewById(R.id.tvAl);
                TextView tvAll=inflate1.findViewById(R.id.tvAll);
                tvBig.setWidth(llCheckResult.getWidth());
                tvAll.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        level=-1;
                        tvCheckResult.setText("等级");
                        tvCheckResult.setTextColor(context.getResources().getColor(R.color.gray3));
                        popupWindow.dismiss();
                        getData();
                    }
                });

                tvBig.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        //重大隐患
                        level=3;
                        tvCheckResult.setText("重大隐患");
                        tvCheckResult.setTextColor(context.getResources().getColor(R.color.blue_3B5BEA));
                        popupWindow.dismiss();
                        getData();
                    }
                });
                tvCommon.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        //一般隐患
                        level=1;
                        tvCheckResult.setText("一般隐患");
                        tvCheckResult.setTextColor(context.getResources().getColor(R.color.blue_3B5BEA));
                        popupWindow.dismiss();
                        getData();
                    }
                });
                popupWindow = new PopupWindow(inflate1, RelativeLayout.LayoutParams.WRAP_CONTENT,
                        RelativeLayout.LayoutParams.WRAP_CONTENT);
                //设置背景,这个没什么效果，不添加会报错
                popupWindow.setBackgroundDrawable(new BitmapDrawable());
                //设置点击弹窗外隐藏自身
                popupWindow.setFocusable(true);
                popupWindow.setOutsideTouchable(true);
                //相对于某一个控件的位置
                popupWindow.showAsDropDown(llCheckResult,0,-100);
                break;
            case R.id.llCheckTable:
                statusAdapter=new HiddenDangerStatusAdapter(ststusUnHandle);
                View inflate2 = LayoutInflater.from(context).inflate(R.layout.popu_hiddendanger_status,null);
                TextView tvTitle=inflate2.findViewById(R.id.tvTitle);
                RecyclerView rcCommon=inflate2.findViewById(R.id.rcCommon);
                rcCommon.setAdapter(statusAdapter);
                rcCommon.setLayoutManager(new LinearLayoutManager(context));
                tvTitle.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        disposeStatus=-1;
                        tvCheckTable.setText("状态");
                        tvCheckTable.setTextColor(context.getResources().getColor(R.color.gray3));
                        popupWindow.dismiss();
                        getData();
                    }
                });
                statusAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
                    @Override
                    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                        disposeStatus=statusAdapter.getData().get(position).getId();
                        tvCheckTable.setText(statusAdapter.getData().get(position).getText());
                        tvCheckTable.setTextColor(context.getResources().getColor(R.color.blue_3B5BEA));
                        popupWindow.dismiss();
                        getData();
                    }
                });

                tvTitle.setWidth(llCheckTable.getWidth());
                popupWindow = new PopupWindow(inflate2, RelativeLayout.LayoutParams.WRAP_CONTENT,
                        RelativeLayout.LayoutParams.WRAP_CONTENT);
                //设置背景,这个没什么效果，不添加会报错
                popupWindow.setBackgroundDrawable(new BitmapDrawable());
                //设置点击弹窗外隐藏自身
                popupWindow.setFocusable(true);
                popupWindow.setOutsideTouchable(true);
                //相对于某一个控件的位置
                popupWindow.showAsDropDown(llCheckTable,0,-100);
                break;
        }
    }
}
